package com.shujia.flink.source;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo4KafkaSource {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//broker列表
                .setTopics("bigdata")//指定topic
                .setGroupId("Demo4KafkaSource")//消费者组，一条数据在一个组内只消费一次
                .setStartingOffsets(OffsetsInitializer.earliest())//earliest: 从最早开始消费，latest：从最新开始消费
                .setValueOnlyDeserializer(new SimpleStringSchema())//指定读取数据的格式
                .build();

        //使用kafka source
        DataStream<String> linesDS = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");


        linesDS.map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(kv -> kv.f0)
                .sum(1)
                .print();

        env.execute();
    }
}
